#!/usr/bin/env perl

# Draw partitions
# Basile Clout, November 2007

use Getopt::Long;
use File::Basename;
use File::Copy;

use strict;
use warnings;

sub usage(){
  print <<EOF;

drawParts.pl [-d directory] [-p optional processing (such as trim)]
[-n number of partitions drawn among the partitions created (if >
number of partitions, all are drawn)] [-f list of partition files]
<.node file> <.graph file> <list of .part files>

EOF
exit;
}

my $showmesh_bin="./showmesh2.py";
#my $showmesh_bin="/root/export_cluster/code/tools/wcolor/vtk/showmesh2.py";
my $showmesh_fl=" -n graph -i metis -r vtk --vtk_rsphere 0.8 --vtk_png --vtk_filename ";

my $n=0;
my $dir=".";
my $fparts="";
my ($fnode, $fgraph);
my @fparts_l;
my $help;
my $options;

GetOptions("n=i"=>\$n, "d=s"=>\$dir, "h"=>\$help, "f=s"=>\$fparts, "p"=>\$options);


my $list="";
my $png_name;
my $c=0;

if ( ($#ARGV < 2 && $fparts eq "") || $help){
  usage;
}

if (-r $ARGV[0]){
  $fnode=$ARGV[0];
}else{
  die("$fnode node file is not readable");
}

if (-r $ARGV[1]){
  $fgraph=$ARGV[1];
}else{
  die("$fgraph graph file is not readable");
}

if ($#ARGV>1){
  @fparts_l=@ARGV[2..$#ARGV];
}elsif ($fparts ne ""){
  open(FPARTS, $fparts ) or die("Impossible to open partitions file $fparts: $!");
  @fparts_l=<FPARTS>;
  close(FPARTS);
}

if ($dir !~ /^\.*\// and $dir ne "."){
  $dir="./$dir";
}
if ($dir =~ /(.*)\/$/){
  $dir=$1;
}

if (! -d $dir){
  mkdir $dir;
}

# Create graphic representation of some partitions

for my $part (@fparts_l){

  if ($n != 0 and $c>$n-1){
    last;
  }
  chomp $part;
  my ($part_name, $dummy)=fileparse($part);
  $png_name = $part_name;
  print "Draw partition $part in ${dir}/${png_name}.png\n";
  my $order = "$showmesh_bin $showmesh_fl $png_name $fnode $fgraph $part";
  open DRAW, "$order |" or warn("ERROR: Impossible to draw partitions: $!");
  while (my $line = <DRAW>){
    if ($line =~ /Error/i){
      print "Error when processing partition $part\n";
      exit;
    }   
  }
  system("convert -trim +repage -border 5x5 -bordercolor \"#FFFFFF\" $png_name.png $png_name.png") == 0 
    or warn "Impossible to trim the .png image: $?" if ($options);
  move "$png_name.png", $dir;
  $list.="${dir}/${png_name}.png ";

  $c++;
}

if ($options) {
  my $x=int(sqrt $c);
  system("montage -label \%f -mode concatenate -tile ${x}x $list ${png_name}_montage.png ") == 0 or warn "Impossible to create the montage: $?";
  move "${png_name}_montage.png", $dir;
}

